package com.yunbiao.ybbusstopplate.ui.activity

import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.FragmentUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ThreadUtils.SimpleTask
import com.blankj.utilcode.util.UiMessageUtils
import com.blankj.utilcode.util.UiMessageUtils.UiMessage
import com.blankj.utilcode.util.UiMessageUtils.UiMessageCallback
import com.example.library_hy_advert.HYAdvert
import com.yunbiao.communication.ServiceManager
import com.yunbiao.communication.XmppStateObserver
import com.yunbiao.ybbusstopplate.BuildConfig
import com.yunbiao.ybbusstopplate.R
import com.yunbiao.ybbusstopplate.base.APP
import com.yunbiao.ybbusstopplate.base.BaseActivity
import com.yunbiao.ybbusstopplate.base.Constants
import com.yunbiao.ybbusstopplate.base.HeartBeatClient
import com.yunbiao.ybbusstopplate.base.alive.KeepAliveService
import com.yunbiao.ybbusstopplate.doublescreen.SecondaryPresentation
import com.yunbiao.ybbusstopplate.message.CoreInfoHandler
import com.yunbiao.ybbusstopplate.serialport.SerTool
import com.yunbiao.ybbusstopplate.serialport.SerialPortConfig
import com.yunbiao.ybbusstopplate.ui.dialog.LetterErrorDialogTool
import com.yunbiao.ybbusstopplate.ui.fragment.LeshanMainFragment
import com.yunbiao.ybbusstopplate.ui.fragment.MainFragment
import com.yunbiao.ybbusstopplate.ui.fragment.ThreeAreaMainFragment
import com.yunbiao.ybbusstopplate.ui.fragment.VerifyFragment
import com.yunbiao.ybbusstopplate.refactoring.ui.yibin.YibinMainFragment
import com.yunbiao.ybbusstopplate.utils.CommonUtils
import com.yunbiao.ybbusstopplate.utils.LeShanUtils
import com.yunbiao.ybbusstopplate.utils.SmdtUtils
import com.yunbiao.ybbusstopplate.utils.SpTool
import com.yunbiao.ybbusstopplate.utils.core.TYTool
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMessage
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMsgTool
import com.yunbiao.ybbusstopplate.utils.eventbus.EventTAG
import com.yunbiao.ybbusstopplate.refactoring.ui.yibin.ZHXPortAgreement
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_home.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit
import kotlin.math.abs

class HomeActivity :BaseActivity() {

    private var verifyFragment:VerifyFragment?=null
    private var mainFragment:Fragment?=null
    private var secondaryPresentation:SecondaryPresentation?= null

    override fun getLayoutViewId(): Int {
        return R.layout.activity_home
    }

    override fun initData() {
        UiMessageUtils.getInstance().addListener(777,uiMessageCallback)

        HYAdvert.init(APP.getAppContext())

        HeartBeatClient.getInstance()

        //是否开启云服务器
        startServer()

        if (SpTool.getDoubleScreen()) {
            val secondaryDisplay = SecondaryPresentation.getSecondaryDisplay(this)
            if(secondaryDisplay != null && (secondaryPresentation == null || secondaryPresentation?.isShowing == false)){
                secondaryPresentation = SecondaryPresentation(this,secondaryDisplay);
            }
            secondaryPresentation?.show()
        }

        Log.d(TAG, "BuildConfig.FLAVOR_TYPE: " + BuildConfig.FLAVOR_TYPE);

        //保活程序
        KeepAliveService.startKeepAliveService(this)
        EventBus.getDefault().register(this)
        //是否激活
        val appSerialNumber = SpTool.getAppSerialNumber()
        if (TextUtils.isEmpty(appSerialNumber)){
            //验证fragment
            verifyFragment=VerifyFragment.getInstance()
            supportFragmentManager.beginTransaction().replace(R.id.fl_home, verifyFragment!!).commit()
        }
        // 三分区
        else if(BuildConfig.FLAVOR_TYPE == FlavorType.IS_THREE_AREA){
            mainFragment = ThreeAreaMainFragment.getInstance()
            supportFragmentManager.beginTransaction().replace(R.id.fl_home, mainFragment!!).commit()
        }
        // 乐山
        else if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN){
                LeShanUtils.syncTime(object : Observer<List<Int>>{
                    override fun onSubscribe(d: Disposable) {
                        pb_loading.visibility = View.VISIBLE
                    }

                    override fun onNext(t: List<Int>) {

                        val time = SmdtUtils.getInstance().setTime(t[0], t[1], t[2], t[3], t[4])
                        Log.d(TAG, "onNext: 校时：$time");

                        mainFragment = if(BuildConfig.IS_LESHAN_SELF){
                            LeshanMainFragment.getInstance()
                        } else {
                            MainFragment.getInstance()
                        }
                        supportFragmentManager.beginTransaction().replace(R.id.fl_home, mainFragment!!).commit()

                        pb_loading.visibility = View.GONE
                    }

                    override fun onError(e: Throwable) {
                    }

                    override fun onComplete() {
                        pb_loading.visibility = View.GONE
                    }
                })
        } else if(SpTool.getConfigSerialPortType() == SerialPortConfig.TYPE_ZHX){
            mainFragment =
                YibinMainFragment()
            supportFragmentManager.beginTransaction().replace(R.id.fl_home, mainFragment!!).commit()
        } else {
            mainFragment = MainFragment.getInstance()
            supportFragmentManager.beginTransaction().replace(R.id.fl_home, mainFragment!!).commit()
        }

//            //main fragment
//            mainFragment = if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN){
//                if(BuildConfig.IS_LESHAN_SELF){
//                    LeshanMainFragment.getInstance()
//                } else {
//                    MainFragment.getInstance()
//                }
//            } else {
//                MainFragment.getInstance()
//            }
//            supportFragmentManager.beginTransaction().replace(R.id.fl_home, mainFragment!!).commit()

        //创建缓存文件夹
        CommonUtils.getInstance().makesCacheFiles()

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            LogWatcher.getInstance().init(this).startWatch()
//        }

        test()
    }

    private val TAG = "HomeActivity"
    private val uiMessageCallback = UiMessageCallback { localMessage: UiMessage ->
        val timeArray = localMessage.getObject() as IntArray
        val seconds = timeArray[timeArray.size - 1]
        Log.d(TAG, "秒数: $seconds")
        val delay = 60 - seconds - 5
        Log.d(TAG, "延迟重启: $delay")
        val lastTime = System.currentTimeMillis()
        ThreadUtils.executeByCachedWithDelay<Int>(object : SimpleTask<Int?>() {
            @Throws(Throwable::class)
            override fun doInBackground(): Int {
                Log.e(TAG, "doInBackground: 设置时间")
                return SmdtUtils.getInstance().setTime(timeArray[0], timeArray[1], timeArray[2], timeArray[3], timeArray[4])
            }

            override fun onSuccess(result: Int?) {
                Log.d(TAG, "onSuccess: " + System.currentTimeMillis() + " --- " + lastTime)
                //判断设置后时间比设置前时间超过30秒就重启
                if (abs(System.currentTimeMillis() - lastTime) > 30 * 1000) {
                    Log.d(TAG, "onSuccess: 设置时间重启")
                    AppUtils.relaunchApp(true)
                }
            }
        }, delay.toLong(), TimeUnit.SECONDS)
    }

    fun test(){
        if(!BuildConfig.DEBUG){
            return
        }

//        TMPortAgreement.getInstance();

        btn_list.visibility = View.VISIBLE
        btn_list.setOnClickListener {
            ZHXPortAgreement.getInstance().test()
//            HXPortAgreement.getInstance().test()
//            TD2020PortAgreement.getInstance().test1()
//            LSTKPortAgreement.getInstance().testList()
//            LSPortAgreement.getInstance().testSiteList()
//            TMPortAgreement.getInstance().testInfo()
//            LTYPortAgreement.getInstance().testSiteList("")
//            HYPortAgreement.getInstance().testInfo()
//            TD2020PortAgreement.getInstance().test1()
        }

        var index = 16
        btn_next.visibility = View.VISIBLE
        btn_next.setOnClickListener {
            UiMessageUtils.getInstance().send(
                ZHXPortAgreement.Event.BROAD_SITE.ordinal, arrayOf(
                "当前站","下一站",index
            ))
            index += 1;
//            LSTKPortAgreement.getInstance().testBroad()
//            LSPortAgreement.getInstance().testNext()
//            TMPortAgreement.getInstance().next()
//            LTYPortAgreement.getInstance().testSite()
//            HYPortAgreement.getInstance().testInOut()
//            TD2020PortAgreement.getInstance().test2()
        }

        btn_query.visibility = View.VISIBLE
        btn_query.setOnClickListener {
//            LSTKPortAgreement.getInstance().testUpDown()
//            TMPortAgreement.getInstance().query()
//            HYPortAgreement.getInstance().testInfo()
//            TD2020PortAgreement.getInstance().test3()
        }

        btn_up.visibility = View.VISIBLE
        btn_up.setOnClickListener{
//            LTYPortAgreement.getInstance().testLineInfo("00")
//            LTYPortAgreement.getInstance().testSiteList("00")
//            TD2020PortAgreement.getInstance().test4()
        }

        btn_down.visibility = View.VISIBLE
        btn_down.setOnClickListener{
//            LTYPortAgreement.getInstance().testLineInfo("01")
//            LTYPortAgreement.getInstance().testSiteList("01")
        }
    }
    private fun  startServer(){
        val isOnline = SpTool.getConfigAdvertServerType()
        if (!isOnline){
            return
        }
        val address=SpTool.getServerAddress()
        val port=SpTool.getServerPort()

        if (!TextUtils.isEmpty(address)&&!TextUtils.isEmpty(address)) {
         Constants.initConstant(address, port)
        }else{
            return
        }
        //true代表跟服务器不一样 更新布局
        TYTool.downloadResource()

        CommonUtils.saveBroadInfo() //保存主板信息

        Log.e("server", "address------------->"+address )
        ServiceManager.getInstance().init(this@HomeActivity, CoreInfoHandler(), object :
            ServiceManager.getUserNameCallback {
            override fun getUserName(): String = HeartBeatClient.getDeviceNo()
            override fun getCommunicationAddress(): String = address
            override fun getCommunicationPort(): String = Constants.XMPP_PORT
        })
        ServiceManager.getInstance().startService()
        try {
            ServiceManager.getInstance().registerObserver(
                XmppStateObserver {
                    Log.e("xmpp", "start: ---------it-------->" + it)

                })


        } catch (e: Exception) {
            Log.d(TAG, "ServiceManager.getInstance().registerObserver exception " + e)
        }
    }

    override fun onDestroy() {
        UiMessageUtils.getInstance().removeListener(777, uiMessageCallback)
        if(secondaryPresentation?.isShowing == true){
            secondaryPresentation?.dismiss()
        }
        try {
            LogUtils.e("HomeActivity destroy!!!")
        } catch (e: Exception) {
        }
//        LogWatcher.getInstance().stopWatch()
        //关闭保活程序
        KeepAliveService.stopKeepAliveService(this)
        EventBus.getDefault().unregister(this)
        //关闭串口
        SerTool.closePort()
        //关闭通信失败dialog
        LetterErrorDialogTool.dismissLetterErrorDialog()

        try {
            ServiceManager.getInstance().stopService()
        } catch (e: Exception) {
        }
        super.onDestroy()
    }

    private var mExitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if (onBackKeyListener!=null){
                onBackKeyListener!!.onBack()
                return true
            }
            if (System.currentTimeMillis() - mExitTime > 2000) { //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis()
                return true
            } else { //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                return super.onKeyDown(keyCode, event)
            }
        }else if (keyCode==KeyEvent.KEYCODE_MENU){
            if (mainFragment!=null){
                EventMsgTool.getInstance().postShowConfig()
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventResult(eventMessage: EventMessage){
        Log.d(TAG, "BuildConfig.FLAVOR_TYPE: " + BuildConfig.FLAVOR_TYPE);
        Log.d(TAG, "eventMessage.msgTag 路？ " + eventMessage.msgTag);

        when(eventMessage.msgTag){
            //跳转main fragment
            EventTAG.EVENT_TOMAIN -> {
                mainFragment = if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN){
                    if(BuildConfig.IS_LESHAN_SELF){
                        LeshanMainFragment.getInstance()
                    }
                    else {
                        MainFragment.getInstance()
                    }
                } else {
                    Log.d("info", "选择 mainFragment")
                    MainFragment.getInstance()
                }

                FragmentUtils.replace(
                    supportFragmentManager,
                    mainFragment!!,
                    R.id.fl_home,
                    R.anim.fragment_slide_right_in,
                    R.anim.fragment_slide_left_out
                )
            }
        }
    }

}